<template>
  <div class="image_list">
    <el-card class="box-card" shadow="hover">
      <el-radio-group v-model="college" @change="loadImages(1)" size="mini">
        <el-radio-button label="false">全部</el-radio-button>
        <el-radio-button label="true">收藏</el-radio-button>
      </el-radio-group>
      <el-button
        style="float: right"
        @click="dialogTableVisible = true"
        type="success"
        size="mini"
        v-if="isShowAdd"
        >上传素材</el-button
      >
      <!-- 素材列表 -->
      <el-row :gutter="20">
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
          v-for="(img, index) in images"
          :key="index"
          @click.native="selected = index"
          class="list_img_item"
        >
          <el-image class="list_images" :src="img.url" fit="cover"> </el-image>
          <div class="list_img_footer" v-if="isShowAdd">
            <!--
              class 样式绑定
              {
                  CSS类名: 布尔值
              }
              true：作用类名
              false：不作用类名
            -->
            <el-button
              type="warning"
              :icon="img.is_collected ? 'el-icon-star-on' : 'el-icon-star-off'"
              @click="onCollect(img)"
              circle
              :loading="img.loading"
              size="mini"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              :loading="img.loading"
              @click="onDelete(img)"
              size="mini"
            >
            </el-button>
          </div>
          <div
            class="list_img_selected"
            v-if="isShowSelected && selected === index"
          ></div>
        </el-col>
      </el-row>
      <!-- 数据分页 -->
      <!--
      分页数据改变以后，页码不会变化
      它需要单独处理高亮的页码
    -->
      <el-pagination
        background
        @current-change="onPageChange"
        layout="prev, pager, next"
        :current-page.sync="page"
        :page-size="pageSize"
        :total="totalCount"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="图片上传"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
      width="21%"
      :append-to-body="true"
    >
      <!--
        upload 组件本身就支持请求提交上传操作，说白了你使用它不用自己去发请求，它会自己发。
        请求方法：默认就是 POST
        请求路径：action，必须写完整路径
        请求头：headers
      -->
      <el-upload
        :show-file-list="false"
        class="upload-demo"
        drag
        :headers="uploadHeaders"
        name="image"
        :on-success="onUploadSuccess"
        action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { getImages, collectImage, deleteImage } from "@/api/image";
export default {
  name: "ImageList",
  // 使用对象的方式定义 prop，更严谨，功能更丰富，强烈建议在项目中使用
  props: {
    // 是否显示添加素材
    isShowAdd: {
      type: Boolean,
      default: true,
    },
    // 是否显示图片勾选状态
    isShowSelected: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const user = JSON.parse(window.localStorage.getItem("user"));
    return {
      college: false, // 默认查询全部素材列表
      images: [], // 图片素材
      dialogTableVisible: false,
      uploadHeaders: {
        Authorization: `Bearer ${user.token}`,
      },
      totalCount: 0, // 总数据条数
      pageSize: 20, // 每页大小
      page: 1, // 当前页码
      selected: null, // 选中的索引
    };
  },
  created() {
    // 页面初始化加载第 1 页数据
    this.loadImages(1, false);
  },
  methods: {
    loadImages(page = 1) {
      // 重置高亮页码，防止数据和页码不对应
      this.page = page;
      getImages({
        collect: this.college,
        page,
        per_page: this.pageSize,
      }).then((res) => {
        const results = res.data.data.results;
        results.forEach((img) => {
          // img 对象本来没有 loading 数据
          // 我们这里收到的往里面添加该数据是用来控制每个收藏按钮的 loading 状态
          img.loading = false;
        });
        this.images = results;
        this.totalCount = res.data.data.total_count;
      });
    },
    onUploadSuccess() {
      // 关闭对话框
      this.dialogTableVisible = false;
      // 更新素材列表
      this.loadImages(this.page);
      this.$message({
        type: "success",
        message: "上传成功",
      });
    },
    onPageChange(page) {
      this.loadImages(page);
    },
    onCollect(img) {
      // 展示 loading
      img.loading = true;
      collectImage(img.id, !img.is_collected).then((res) => {
        // 更新视图状态
        img.is_collected = !img.is_collected;
        // 关闭 loading
        img.loading = false;
      });
    },
    onDelete(img) {
      img.loading = true;
      deleteImage(img.id).then((res) => {
        // 重新加载数据列表
        this.loadImages(this.page);
        img.loading = false;
      });
    },
  },
};
</script>

<style scoped lang="less">
.list_img_item {
  position: relative;
  .list_images {
    width: 240px;
    height: 240px;
    -webkit-user-drag: none;
    margin-top: 30px;
  }
  .list_img_selected {
    width: 80px;
    height: 80px;
    background: url(./selected.png) no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: 80%;
    left: 45%;
    margin-left: -40px;
    margin-top: -40px;
  }
  .list_img_footer {
    height: 30px;
    width: 240px;
    cursor: pointer;
    position: absolute;
    bottom: 16px;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    color: rgb(255, 255, 255);
  }
}
</style>
